import json

from common.setting import ensure_path_sep
from utils.logging_tool.log_decorator import log_print_decorator_temu_publish
from utils.models import StrategyRuleTemuOne, StrategyRuleTemu
from utils.mysqlUtils.db_pool import Database
from apps.zhcxkj_center_product.test.views.get_sku_goor_num_by_set import Inventory
switch = True
class TestFilterPublish:

    def __init__(self, strategy_id):
        self.strategy_id = strategy_id

        zhcxkj_center_strategy_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                           "test_jdw_database")
        get_ = f"""
        SELECT * 
        FROM test_zhcxkj_center_strategy_comprehensive.`t_strategy_rule_temu` 
        WHERE strategy_id= %s
        and status =1
        """
        t_strategy_rule_temu = zhcxkj_center_strategy_comprehensive_db.fetch_all(get_, (strategy_id,))
        strategy_rule_temu = {}
        for one in t_strategy_rule_temu:
            strategy_rule_temu[one.get('rule_code')] = StrategyRuleTemuOne(**one)
        get_import_data = f"""
        SELECT import_val 
        FROM test_zhcxkj_center_strategy_comprehensive.`t_strategy_import_filter_temu` 
        WHERE import_id= %s
        """
        import_val_list = zhcxkj_center_strategy_comprehensive_db.fetch_all_tuple(get_import_data, (strategy_id,))
        if len(import_val_list):
            sku_list = list(map(lambda x: x[0], import_val_list))
            strategy_rule_temu['sku_list'] = sku_list
        self.StrategyRuleTemuList = StrategyRuleTemu(**strategy_rule_temu)

    def filter_publish(self, sku_list,source_id):

        """
        publish_type   filter_val 0 单体  1 变体
        product_model   filter_val：
        sku_available_stock
        pf_no_sale_site
        product_risk_level
        sku_republish_detect
        price_calculator_set_value
        saleable_num
        import_sku
        """
        if self.StrategyRuleTemuList.publish_type.filter_val == "1":
            # 一变多
            sku_list = self.analysis_sku(sku_list=sku_list)
        # t_product_sku_temu_info
        sku_list = self.filter_t_product_sku_temu_info(sku_list=sku_list)
        # 禁售
        sku_list = self.filter_pf_no_sale_site(sku_list=sku_list)
        # 高危
        sku_list = self.filter_product_risk_level(sku_list = sku_list)
        # 仿牌
        sku_list = self.filter_product_property(sku_list=sku_list)
        # 可用库存
        sku_list = self.filter_sku_available_stock(sku_list = sku_list,source_id=source_id)
        # listing表过滤
        sku_list = self.filter_sku_republish_detect(sku_list = sku_list,source_id=source_id)
        # 过滤正在刊登的sku以及近一小时刊登成功的sku
        self.filter_t_publish_detail_temu(sku_list=sku_list,source_id=source_id)
        self.filter_t_product_temu_attribute(sku_list=sku_list)

        print(f"预期{set(sku_list)}")
        actual_res = self.get_actual_result(self.strategy_id, source_id)
        print(f"实际{set(actual_res)}")
        if set(sku_list) != set(actual_res):
            print(set(sku_list) - set(actual_res))
    def get_actual_result(self,strategy_id,source_id):
        zhcxkj_center_strategy_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                           "test_jdw_database")
        get_data = f"""
        select sku 
        from test_zhcxkj_center_strategy_comprehensive.t_publish_detail_temu
        where strategy_id= %s
        and source_id= %s
--         and create_time >= now()
        """
        data = zhcxkj_center_strategy_comprehensive_db.fetch_all_tuple(get_data,(strategy_id,source_id))
        sku_list = []
        if len(data):
            sku_list = list(map(lambda x: x[0], data))
        return sku_list

    def analysis_sku(self,sku_list):
        zhcxkj_center_product_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")

        get_ = f"""
        select sku,product_group_sku
        from test_zhcxkj_center_product.rb_product
        where sku in %s
        """
        res = zhcxkj_center_product_db.fetch_all_tuple(get_, (sku_list,))
        finally_sku_list = []
        product_group_sku_list = []
        for sku,product_group_sku in res:
            if product_group_sku == "":
                finally_sku_list.append(sku)
            else:
                product_group_sku_list.append(product_group_sku)
        if product_group_sku_list:

            get_product_group_sku_list = f"""
            select sku 
            from test_zhcxkj_center_product.rb_product
            where  product_group_sku in %s
            """
            product_group_sku_list_res  =  zhcxkj_center_product_db.fetch_all_tuple(get_product_group_sku_list, (product_group_sku_list,))
            product_group_sku_list = list(map(lambda x: x[0], product_group_sku_list_res))
        finally_sku_list.extend(product_group_sku_list)
        return finally_sku_list
    # 平台禁售
    # 产品风险等级
    # sku重刊检测
    @log_print_decorator_temu_publish(switch=switch, filter_mame="禁售sku")
    def filter_pf_no_sale_site(self, sku_list):

        zhcxkj_center_product_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")

        filter_val = self.StrategyRuleTemuList.pf_no_sale_site.filter_val
        # 序列化
        filter_val = json.loads(filter_val)
        # {"platforms":[125,1],"sites":[1,2,3]}
        platforms = filter_val.get('platforms')
        sites = filter_val.get('sites')
        no_sale_sku_list = []
        get_sku_list_have_country_shorthand = f"""
        select distinct sku
        from test_zhcxkj_center_product.rb_product_no_sale
        where platform_type = %s
        and ( country_shorthand in %s or country_shorthand = '')
        and sku in %s
        """
        get_sku_list_have_ = f"""
        select distinct sku
        from test_zhcxkj_center_product.rb_product_no_sale
        where platform_type = %s
        and sku in %s
        """
        if sites:
            platform_type_site_list = TestFilterPublish.analysis_platforms_sites(platforms,sites)
            for platform_type, site_code in platform_type_site_list.items():

                if site_code:
                    sku_ = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list_have_country_shorthand,
                                                                    (platform_type, site_code, sku_list))
                else:
                    sku_ = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list_have_,
                                                                    (platform_type, sku_list))
                if len(sku_):
                    no_sale_sku_list.extend(list(map(lambda x: x[0], sku_)))
        else:
            for platform_type in platforms:
                sku_ = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list_have_,
                                                                (platform_type, sku_list))
                if len(sku_):
                    no_sale_sku_list.extend(list(map(lambda x: x[0], sku_)))

        return list(filter(lambda x: x not in no_sale_sku_list,sku_list))

    @staticmethod
    def analysis_platforms_sites(platforms:list,sites:list):
        zhcxkj_center_data_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        get_platform_type_site_code = f"""
        SELECT platform_type,site_code
        FROM test_zhcxkj_center_data.t_platform_site
        WHERE id in %s
        """
        platform_type_site_code = zhcxkj_center_data_db.fetch_all_tuple(get_platform_type_site_code, (sites,))

        platform_type_site_list = dict()
        # {1:["JP","AU"],67:["pl"]}
        for platform_type, site_code in platform_type_site_code:
            if platform_type not in platform_type_site_list:
                platform_type_site_list[platform_type] = []
                platform_type_site_list[platform_type].append(site_code)
            else:
                platform_type_site_list[platform_type].append(site_code)
        for platform_type in platforms:
            if int(platform_type) not in platform_type_site_list:
                platform_type_site_list[int(platform_type)] = []
        return platform_type_site_list

    @log_print_decorator_temu_publish(switch=switch, filter_mame="高危sku")
    def filter_product_risk_level(self, sku_list):
        zhcxkj_center_product_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        filter_val = self.StrategyRuleTemuList.product_risk_level.filter_val
        filter_val = json.loads(filter_val)
        if filter_val.get('riskLevel') != 1:
            return sku_list
        platforms = filter_val.get('platforms')
        sites = filter_val.get('sites')
        get_no_hisk_sku_list = f"""
        select sku
        from test_zhcxkj_center_product.rb_product_admin
        where sku in %s
        and risk_level_type = 0
        """
        no_hisk_sku_list_res = zhcxkj_center_product_db.fetch_all_tuple(get_no_hisk_sku_list,(sku_list,))
        no_hisk_sku_list = []
        if len(no_hisk_sku_list_res):
            no_hisk_sku_list = list(map(lambda x: x[0], no_hisk_sku_list_res))
        sku_list = list(filter(lambda x: x not in no_hisk_sku_list,sku_list))
        product_risk_level_sku = []
        get_sku_list_have_country_shorthand = f"""
        select distinct sku
        from test_zhcxkj_center_product.rb_product_risk_level_platform
        where platform_type = %s
        and ( country_shorthand in %s or country_shorthand = '')
        and sku in %s
        """
        get_sku_list_have_ = f"""
        select distinct sku
        from test_zhcxkj_center_product.rb_product_risk_level_platform
        where platform_type = %s
        and sku in %s
        """
        if sites:
            platform_type_site_list = TestFilterPublish.analysis_platforms_sites(platforms,sites)

            for platform_type, site_code in platform_type_site_list.items():

                if site_code:
                    sku_ = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list_have_country_shorthand,
                                                                    (platform_type, site_code, sku_list))
                else:
                    sku_ = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list_have_,
                                                                    (platform_type, sku_list))
                if len(sku_):
                    product_risk_level_sku.extend(list(map(lambda x: x[0], sku_)))
        else:
            for platform_type in platforms:
                sku_ = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list_have_,
                                                                (platform_type, sku_list))
                if len(sku_):
                    product_risk_level_sku.extend(list(map(lambda x: x[0], sku_)))

        return list(filter(lambda x: x not in product_risk_level_sku, sku_list)) + no_hisk_sku_list

    @log_print_decorator_temu_publish(switch=switch, filter_mame="重刊")
    def filter_sku_republish_detect(self, sku_list,source_id):
        zhcxkj_center_listing_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        filter_val = self.StrategyRuleTemuList.sku_republish_detect.filter_val
        if filter_val != 1:
            return sku_list
        no_publish_sku_list = []
        get_no_publish_sku_list = f"""
        select b.sku
        from test_zhcxkj_center_listing_comprehensive.t_temu_listing a
        left join test_zhcxkj_center_listing_comprehensive.t_temu_listing_sku b on a.id=b.listing_id
        where a.source_id = %s
        and a.select_status in (17,13,9,0)
        and b.sku in %s
        """
        no_publish_sku_list_res = zhcxkj_center_listing_comprehensive_db.fetch_all_tuple(get_no_publish_sku_list,(source_id,sku_list))
        if len(no_publish_sku_list_res):
            no_publish_sku_list = list(map(lambda x: x[0], no_publish_sku_list_res))
        return list(filter(lambda x: x not in no_publish_sku_list,sku_list))

    @log_print_decorator_temu_publish(switch=switch, filter_mame="t_product_sku_temu_info")
    def filter_t_product_sku_temu_info(self,sku_list):
        zhcxkj_center_product_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        get_sku_list = f"""
        select sku
        from test_zhcxkj_center_product.t_product_sku_temu_info
        where sku in %s
        and status =1
        and is_deleted=0 
        """
        sku_list_res = zhcxkj_center_product_db.fetch_all_tuple(get_sku_list,(sku_list,))
        return list(map(lambda x: x[0], sku_list_res)) if len(sku_list_res) else []

    @log_print_decorator_temu_publish(switch=switch, filter_mame="t_publish_detail_temu")
    def filter_t_publish_detail_temu(self, sku_list, source_id):
        zhcxkj_center_strategy_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                          "test_jdw_database")
        no_publish_sku_list = []
        get_no_publish_sku_list = f"""
        select a.sku
        from test_zhcxkj_center_strategy_comprehensive.t_publish_detail_temu a
        where a.source_id = %s
        and a.pub_status in (0,1,2,6)
        and a.sku in %s
        union all
        select a.sku
        from test_zhcxkj_center_strategy_comprehensive.t_publish_detail_temu a
        where a.source_id = %s
        and a.pub_status = 4
        and a.sku in %s
        and pub_time >= DATE_SUB(NOW(),INTERVAL 1 HOUR )
        """
        no_publish_sku_list_res = zhcxkj_center_strategy_comprehensive_db.fetch_all_tuple(get_no_publish_sku_list,
                                                                                         (source_id, sku_list,source_id, sku_list))
        if len(no_publish_sku_list_res):
            no_publish_sku_list = list(map(lambda x: x[0], no_publish_sku_list_res))
        return list(filter(lambda x: x not in no_publish_sku_list, sku_list))

    @log_print_decorator_temu_publish(switch=switch, filter_mame="t_product_temu_attribute")
    def filter_t_product_temu_attribute(self, sku_list):
        zhcxkj_center_attribute_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                           "test_jdw_database")
        get_sku_list = f"""
        select sku 
        from test_zhcxkj_center_attribute.t_product_temu_attribute
        where sku in %s
        and is_deleted = 0
        """
        sku_list_res = zhcxkj_center_attribute_db.fetch_all_tuple(get_sku_list, (sku_list,))
        filter_sku_list = []
        if len(sku_list_res):
            filter_sku_list = list(map(lambda x: x[0], sku_list_res))
        return filter_sku_list

    @log_print_decorator_temu_publish(switch=switch, filter_mame="仿牌")
    def filter_product_property(self, sku_list):
        zhcxkj_center_product_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")

        get_ = f"""
        select sku,product_property
        from test_zhcxkj_center_product.rb_product
        where sku in %s
        """
        res = zhcxkj_center_product_db.fetch_all_tuple(get_, (sku_list,))
        return list(map(lambda x:x[0],list(filter(lambda x: x[1] in [1,3],res))))

    @log_print_decorator_temu_publish(switch=switch, filter_mame="可用库存")
    def filter_sku_available_stock(self, sku_list, source_id):
        if self.StrategyRuleTemuList.sku_available_stock.filter_min_val == "":
            return sku_list
        filter_min_val = int(self.StrategyRuleTemuList.sku_available_stock.filter_min_val)
        filter_max_val = int(self.StrategyRuleTemuList.sku_available_stock.filter_max_val)
        zhcxkj_center_listing_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        get_warehouseCode_list = f"""
        SELECT * FROM test_zhcxkj_center_listing_comprehensive.t_temu_warehouse_setting 
        WHERE source_id={source_id}
        """
        warehouseCode_list = zhcxkj_center_listing_comprehensive_db.fetch_all(get_warehouseCode_list,())
        warehouseCode_list = list(map(lambda x:x.get('warehouseCode'),json.loads(warehouseCode_list[0].get('pop_choice_warehouse'))))

        sku_good_num_total = Inventory(set(sku_list),set(map(int,warehouseCode_list)),False).get_set()

        return list(filter(lambda x: filter_min_val <= sku_good_num_total.get(x,0) <= filter_max_val,sku_list))


if __name__ == '__main__':
    TestFilterPublish(8).filter_product_risk_level(["4545072", "16444064", "6846976"])
